const jwt = require("jsonwebtoken");
const {
  tokenExpiredError,
  invalidToken,
  noPermission,
} = require("../constant/err.type");
const { JWT_SECRET } = require("../config/config.default");



// 验证token
const auth = async (ctx, next) => {
  const { authorization } = ctx.request.header;
  const token = authorization.replace("Bearer ", "");

  try {
    const user = jwt.verify(token, JWT_SECRET);
    ctx.state.user = user;
    console.log(user);
  } catch (err) {
    console.log(err);
    switch (err.name) {
      case "TokenExpiredError":
        console.error("token已过期");
        ctx.app.emit("error", tokenExpiredError, ctx);
        return;
      case "JsonWebTokenError":
        console.error("无效的token");
        ctx.app.emit("error", invalidToken, ctx);
        return;
      default:
        console.error("无效的token");
        ctx.app.emit("error", invalidToken, ctx);
        ctx.throw(401, "无效的token");
        return;
    }
  }

  await next();
};
// 验证权限
const hasAdminPermission = async (ctx, next) => {
  const { user_type } = ctx.state.user;
  if (user_type !== 0) {
    console.error("没有权限访问,请联系管理员");
    ctx.app.emit("error", noPermission, ctx);
    return;
  }
  await next();
};



module.exports = {
  auth,
  hasAdminPermission,
};
